package codeRandomThoughts.Test135分发糖果;

import java.util.*;

public class Solution {
    public int candy(int[] ratings) {
        //创建一个数组保存每个孩子给的糖果数目
        int[] candy = new int[ratings.length];

        TreeMap<Integer, List<Integer>> treeMap = new TreeMap<>();
        for (int i = 0; i < ratings.length; i++) {
            List<Integer> list = treeMap.getOrDefault(ratings[i], new ArrayList<>());
            list.add(i);
            treeMap.put(ratings[i], list);
        }

        //遍历treeMap,给candy[]赋值
        Collection<List<Integer>> values = treeMap.values();
        for (List<Integer> indexes : values) {
            for (Integer index : indexes) {
                setCandy(ratings, candy, index);
            }
        }

        return Arrays.stream(candy).sum();
    }

    public void setCandy(int[] ratings, int[] candy, int index) {
        int leftCandy = 0;
        int rightCandy = 0;

        //获取右边的糖果数
        if (index + 1 <= candy.length - 1 && ratings[index] != ratings[index + 1]) rightCandy = candy[index + 1];

        //获取左边的糖果数
        if (index - 1 >= 0 && ratings[index] != ratings[index - 1]) leftCandy = candy[index - 1];

        //设置当前位置的糖果数
        candy[index] = Integer.max(leftCandy, rightCandy) + 1;
    }
}
